<template>
	<div>
	  <el-dialog :title="data.titleName" v-model="data.isopen" :close-on-click-modal='false'
				 :append-to-body='true' width="800px">


				 <div class="container">
		<div class="plugins-tips">通过 v-permiss 自定义指令实现权限管理，使用非 admin 账号登录，可查看效果。</div>
		<div class="mgb20">
			<!-- <span class="label">角色：</span>

			<el-select v-model="role" class="m-2" placeholder="Select" @change="handleChange">
    <el-option
      v-for="item in data.options"
      :key="item.id"
      :label="item.name"
      :value="item.id"
    />
  </el-select> -->

			
		</div>
		<div class="mgb20 tree-wrapper">
			<el-tree
				ref="tree"
		 		:data="data.treelist"
				:props="defaultProps"
				node-key="id"
				default-expand-all
				show-checkbox
				:default-checked-keys="checkedKeys"
			/>
		</div>
		<el-button type="primary" @click="onSubmit(ruleFormRef)">保存权限</el-button>
	</div>
	   <!-- <permission></permission> -->
	  </el-dialog>
	</div>
  </template>
  <script lang="ts" setup>
  import { admingroupdata} from '../../../api/index';
import { usePermissStore } from '../../../store/permiss';
  import {
	ElMessage,
	ElTree
  } from "element-plus";
//   import permission from '../views/permission.vue'
  
  import {
	ref,
	reactive,
	nextTick,
	// defineProps,//defineProps声明props;具备完整的类型推断;<script setup>直接可用
	// defineEmits,//defineEmits声明事件;具备完整的类型推断;<script setup>直接可用
	// defineExpose//暴露出去;<script setup>直接可用
  } from 'vue';
  
  
  const test1 = ref('')
  const test2 = ref('')
  
  const ruleFormRef = ref();//表单ref
  //获取tree选中的值
  const treeRef = ref < InstanceType < typeof ElTree >> ();
  const emit = defineEmits(["onItemChange"]);//声明事件(父级页面上添加的 @监听事件)
  const defaultProps = {
  children: 'childlist',
  label: 'title',
}
  //数据双向绑定;复杂类型数据=>响应式数据
  const data = reactive({
// 	Tree : [
// 	{
// 		id: '1',
// 		label: '系统首页'
// 	},
// 	{
// 		id: '2',
// 		label: '基础表格',
// 		children: [
// 			{
// 				id: '15',
// 				label: '编辑'
// 			},
// 			{
// 				id: '16',
// 				label: '删除'
// 			}
// 		]
// 	},
// 	{
// 		id: '3',
// 		label: 'tab选项卡'
// 	},
// 	{
// 		id: '4',
// 		label: '表单相关',
// 		children: [
// 			{
// 				id: '5',
// 				label: '基本表单'
// 			},
// 			{
// 				id: '6',
// 				label: '文件上传'
// 			},
// 			{
// 				id: '7',
// 				label: '三级菜单',
// 				children: [
// 					{
// 						id: '8',
// 						label: '富文本编辑器'
// 					},
// 					{
// 						id: '9',
// 						label: 'markdown编辑器'
// 					}
// 				]
// 			}
// 		]
// 	},
// 	{
// 		id: '10',
// 		label: '自定义图标'
// 	},
// 	{
// 		id: '11',
// 		label: 'schart图表'
// 	},

// 	{
// 		id: '13',
// 		label: '权限管理'
// 	},
// 	{
// 		id: '14',
// 		label: '支持作者'
// 	}
// ],
options:[{
	  name: '角色组',
	  id: 'water'
	}],
treelist: [],
	titleName: '编辑',
	checkAll: false,
	isopen: false,
	isAdd: false,
	systems: [{
	  name: '开发1部',
	  id: 'water'
	}, {
	  name: '市场部',
	  id: 'pollution'
	}],
	nowKeys: [] as any[], // 属性需要做类型断言处理 //树-选中数据
	treeDatas: [], //树-总数据
	id: '',
	children_page: false,
	dataText:'',
  });
  //ts类型断言
  //定义类型



  interface User {
	rules:string
	type: string
	key: string
	id: string
	openid: string;
	card: string;
	pay: string;
	zone: string;
	sign: string;
	senseuser: string;
	sensedrp: string;
	contime: string;
	block:string;
	con1:string;
	con2:string;
	con3:string;
	con4:string;
	con5:string;
	con6:string;
	con7:string;
	con8:string;
	con9:string;
	con10:string;
  };
  const ruleForm = reactive({
	openid: "",
	card:  "",
	pay:  "",
	zone: "",
	sign:  "",
	senseuser: "",
	sensedrp:  "",
	contime:  "",
	block: "",
	con1: "",
	con2: "",
	con3: "",
	con4: "",
	con5: "",
	con6: "",
	con7: "",
	con8: "",
	con9: "",
	con10: "",
  });
  const rules = ref({
	username: [{
	  required: true,
	  message: '请输入角色名称',
	  trigger: 'blur'
	},
	  {
		min: 1,
		max: 50,
		message: '长度在 1 到 50 个字符',
		trigger: 'blur'
	  }
	],
  
  });


   //获取初始数据
    onMounted(async () => {
        await getAllListLink();
		// getxlk();
		
	});
	 //获取表格列表数据
	 const getAllListLink = async () => {
        let params = {
			action:'apiroletreelist',
        }
        const res = await admingroupdata(params);
        console.log(res);
        console.log(res.status);
                if (res.status == 200) {
                data.treelist = res.data.data
            } else if (res.status !== 200) {
                data.dataText = "暂无数据";
                ElMessage({
                    showClose: true,
                    message: res.statusText,
                    type: 'error',
                })
            }

    };
		 //获取下拉框数据

    const getxlk = () => {
        let params = {
			action:'apiroletreexlk',
        }

        admingroupdata(params).then(res => {
			console.log(res)
			    if (res.status == 200) {
					data.options = res.data.data
					console.log(data.options);
                    ElMessage({
                        showClose: true,
                        message: '操作成功',
                        type: 'success',
                    })
                } else if (res.status !== 200) {
                    ElMessage({
                        showClose: true,
                        message: res.data.msg,
                        type: 'error',
                    })
                }
            })
    };

// 保存权限
const tree = ref<InstanceType<typeof ElTree>>();
   // 获取当前权限
const checkedKeys = ref<string[]>([]);
  //父调子的子
  const addItemShow = (now_name: string) => {
	data.titleName = '添加';
	data.isopen = !data.isopen;
	data.isAdd = true;

	data.nowKeys = []; //树-选中数据
	nextTick(() => {
	checkedKeys.value = [];//重置
	//   checkedKeys.value=row.rules.split(",");
	//  console.log(checkedKeys.value);
	})
	// nextTick(() => {
	// 	  tree.value.setCheckedKeys([]);
    //   });
  };
  //父调子的子
  const addItemShow2 = (row: User, now_name: string) => {
	data.titleName = '编辑';
	data.isopen = !data.isopen;
	data.isAdd = false;
	nextTick(() => {
		checkedKeys.value = [];//重置
	  checkedKeys.value=row.rules.split(",");
	 console.log(checkedKeys.value);
	  data.id = row.id;
	  data.nowKeys = [] //树-选中数据
	  data.treeDatas = [] //树-总数据
	})
	// nextTick(() => {
	// 	  tree.value.setCheckedKeys([]);
    //   });
  };
  defineExpose({
	addItemShow,
      addItemShow2
  }) //将子组件方法暴露出来，让父组件调用

   //添加/修改   : FormInstance | undefined
   const onSubmit = async (formEl:any) => {

          if (data.isAdd) { 
            addRoles();
          } else {
            changeRoles();
          }
		  data.isopen = !data.isopen;
		  await getAllListLink();
    };
// ref的作用是实现响应式， 如果没有ref则不能实现响应式（引用数据类型用reactive）
          // 使用ref包裹的数据，需要通过 .value 的形式访问他的值
    const addRoles = () => { 

		 	// 获取选中的权限
// 	console.log(tree.value!.getCheckedKeys(false));
      console.log(499);
      let params = {
        action: 'apiadd',
		rules: tree.value!.getCheckedKeys(false).join(','),
           
      }
      // 新增
      admingroupdata(params).then(res => {

        if (res.status == 200) {
       
          ElMessage({
            showClose: true,
            message: '操作成功',
            type: 'success',
          })
          data.children_page = true;
          emit("onItemChange");
        } else if (res.status  !== 200) {
          ElMessage.error(res.statusText);
        }
      })
    };
    //修改接口
    const changeRoles = () => {
      // 	// 获取选中的权限
	console.log(tree.value!.getCheckedKeys(false));
      let params = {
        action: 'apiedit',
        id: data.id,
        rules: tree.value!.getCheckedKeys(false).join(','),
      }
admingroupdata(params).then(res => {
        console.log(res)
        console.log(res.status)
        if (res.status == 200) {
          ElMessage({
            showClose: true,
            message: '操作成功',
            type: 'success',
          })
          data.children_page = false;
          emit("onItemChange");//用来子组件调用父组件--刷新列表
        } else if (res.status  !== 200) {
          ElMessage.error(res.statusText);
        }
      })
    };
  
const role = ref<string>('超级管理组');

interface Tree {
	id: string;
	label: string;
	children?: Tree[];
}

 

const permiss = usePermissStore();

// // 获取当前权限
// const checkedKeys = ref<string[]>([]);
// const getPremission = () => {
// 	// 请求接口返回权限
// 	console.log(permiss.defaultList['admin']);
// 	console.log(role.value);
// 	checkedKeys.value = permiss.defaultList[role.value];
// };
// getPremission();

// 保存权限
// const tree = ref<InstanceType<typeof ElTree>>();
// const onSubmit = () => {
// 	// 获取选中的权限
// 	console.log(tree.value!.getCheckedKeys(false));
// };

// const handleChange = (val: string[]) => {
// 	tree.value!.setCheckedKeys(permiss.defaultList[role.value]);
// };










  </script>
  <style scoped>
  .jurisdiction-border {
	width: 500px;
	height: 300px;
	padding: 10px;
	box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
	overflow: auto;
  }
  
  .jurisdiction-border::-webkit-scrollbar {
	width: 7px;
	height: 7px;
	background-color: rgb(241, 241, 241);
	border-radius: 3px;
  }
  
  .jurisdiction-border::-webkit-scrollbar-thumb {
	background-color: rgb(193, 193, 193);
	border-radius: 3px;
  }
  
  /* .tree-name-leave {
	margin-leave: 5px;
  } */
  </style>
  <style>
  .avatar-uploader .el-upload {
	border: 1px dashed #d9d9d9;
	border-radius: 6px;
	cursor: pointer;
	position: relative;
	overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
	border-color: #409EFF;
  }
  .avatar-uploader-icon {
	font-size: 28px;
	color: #8c939d;
	width: 178px;
	height: 178px;
	line-height: 178px;
	text-align: center;
  }
  .avatar {
	width: 178px;
	height: 178px;
	display: block;
  }
  </style>
  